<template>
  <div class="tab-navigation" v-if="tabs.length > 0">
    <div class="tabs-container">
      <!-- 左侧控制按钮 -->
      <div class="tabs-control-left">
        <el-button size="small" text @click="scrollTabs('left')" :disabled="!canScrollLeft">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
      </div>

      <!-- 标签页列表 -->
      <div ref="tabsScrollRef" class="tabs-scroll" @wheel="handleWheel">
        <div class="tabs-list" :style="{ transform: `translateX(${scrollOffset}px)` }">
          <div
            v-for="tab in tabs"
            :key="tab.path"
            class="tab-item"
            :class="{ 
              'is-active': isActive(tab), 
              'is-fixed': tab.fixed,
              'is-modified': tab.modified
            }"
            @click="handleTabClick(tab)"
            @contextmenu.prevent="handleContextMenu($event, tab)"
            @mouseenter="handleTabHover(tab)"
            @mouseleave="handleTabLeave"
          >
            <!-- 标签图标 -->
            <el-icon v-if="tab.icon" class="tab-icon">
              <component :is="tab.icon" />
            </el-icon>
            
            <!-- 标签标题 -->
            <span class="tab-title">{{ tab.title }}</span>
            
            <!-- 修改标记 -->
            <span v-if="tab.modified" class="tab-modified">●</span>
            
            <!-- 关闭按钮 -->
            <el-icon 
              v-if="!tab.fixed && tabs.length > 1" 
              class="tab-close"
              @click.stop="handleClose(tab)"
            >
              <Close />
            </el-icon>

            <!-- 固定图标 -->
            <el-icon v-if="tab.fixed" class="tab-fixed">
              <CircleCheckFilled />
            </el-icon>
          </div>
        </div>
      </div>

      <!-- 右侧控制按钮 -->
      <div class="tabs-control-right">
        <el-button size="small" text @click="scrollTabs('right')" :disabled="!canScrollRight">
          <el-icon><ArrowRight /></el-icon>
        </el-button>
        
        <el-divider direction="vertical" />
        
        <!-- 标签页操作下拉菜单 -->
        <el-dropdown @command="handleCommand">
          <el-button size="small" text>
            <el-icon><More /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="closeOthers">
                <el-icon><Delete /></el-icon>
                关闭其他
              </el-dropdown-item>
              <el-dropdown-item command="closeLeft">
                <el-icon><DArrowLeft /></el-icon>
                关闭左侧
              </el-dropdown-item>
              <el-dropdown-item command="closeRight">
                <el-icon><DArrowRight /></el-icon>
                关闭右侧
              </el-dropdown-item>
              <el-dropdown-item command="closeAll" divided>
                <el-icon><CircleClose /></el-icon>
                关闭全部
              </el-dropdown-item>
              <el-dropdown-item command="refresh" divided>
                <el-icon><Refresh /></el-icon>
                刷新当前
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 右键菜单 -->
    <div 
      v-show="contextMenuVisible" 
      class="context-menu"
      :style="{ left: contextMenuX + 'px', top: contextMenuY + 'px' }"
      @click="contextMenuVisible = false"
    >
      <div class="context-menu-item" @click="handleContextCommand('refresh')">
        <el-icon><Refresh /></el-icon>
        刷新
      </div>
      <div class="context-menu-item" @click="handleContextCommand('close')">
        <el-icon><Close /></el-icon>
        关闭
      </div>
      <div class="context-menu-item" @click="handleContextCommand('closeOthers')">
        <el-icon><Delete /></el-icon>
        关闭其他
      </div>
      <div class="context-menu-divider"></div>
      <div class="context-menu-item" @click="handleContextCommand('pin')">
        <el-icon><PushPin /></el-icon>
        {{ contextTab?.fixed ? '取消固定' : '固定标签' }}
      </div>
      <div class="context-menu-item" @click="handleContextCommand('copyPath')">
        <el-icon><DocumentCopy /></el-icon>
        复制路径
      </div>
    </div>

    <!-- 标签预览（悬停时） -->
    <transition name="fade">
      <div 
        v-if="previewTab" 
        class="tab-preview"
        :style="{ left: previewX + 'px', top: previewY + 'px' }"
      >
        <div class="preview-header">
          <el-icon><component :is="previewTab.icon" /></el-icon>
          <span>{{ previewTab.title }}</span>
        </div>
        <div class="preview-path">{{ previewTab.path }}</div>
        <div class="preview-time">最后访问：{{ formatTime(previewTab.lastVisit) }}</div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft, ArrowRight, Close, More, Delete, DArrowLeft, DArrowRight,
  CircleClose, Refresh, PushPin, DocumentCopy, CircleCheckFilled
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 标签页列表
const tabs = ref([
  {
    path: '/dashboard',
    title: '工作台',
    icon: 'Monitor',
    fixed: true,
    modified: false,
    lastVisit: Date.now()
  }
])

// 滚动相关
const tabsScrollRef = ref(null)
const scrollOffset = ref(0)
const canScrollLeft = ref(false)
const canScrollRight = ref(false)

// 右键菜单
const contextMenuVisible = ref(false)
const contextMenuX = ref(0)
const contextMenuY = ref(0)
const contextTab = ref(null)

// 标签预览
const previewTab = ref(null)
const previewX = ref(0)
const previewY = ref(0)
let previewTimer = null

// 判断是否激活
const isActive = (tab) => {
  return route.path === tab.path
}

// 添加标签页
const addTab = (newTab) => {
  const exists = tabs.value.find(t => t.path === newTab.path)
  if (!exists) {
    tabs.value.push({
      ...newTab,
      modified: false,
      lastVisit: Date.now()
    })
  } else {
    // 更新最后访问时间
    exists.lastVisit = Date.now()
  }
  
  nextTick(() => {
    scrollToActiveTab()
  })
}

// 点击标签
const handleTabClick = (tab) => {
  if (route.path !== tab.path) {
    router.push(tab.path)
  }
}

// 关闭标签
const handleClose = (tab) => {
  const index = tabs.value.findIndex(t => t.path === tab.path)
  
  if (index === -1) return
  
  // 如果关闭的是当前标签，需要跳转到其他标签
  if (isActive(tab)) {
    const nextTab = tabs.value[index + 1] || tabs.value[index - 1]
    if (nextTab) {
      router.push(nextTab.path)
    }
  }
  
  tabs.value.splice(index, 1)
}

// 命令处理
const handleCommand = (command) => {
  const currentIndex = tabs.value.findIndex(t => isActive(t))
  
  switch (command) {
    case 'closeOthers':
      tabs.value = tabs.value.filter((t, i) => t.fixed || i === currentIndex)
      break
    case 'closeLeft':
      tabs.value = tabs.value.filter((t, i) => t.fixed || i >= currentIndex)
      break
    case 'closeRight':
      tabs.value = tabs.value.filter((t, i) => t.fixed || i <= currentIndex)
      break
    case 'closeAll':
      tabs.value = tabs.value.filter(t => t.fixed)
      if (tabs.value.length > 0) {
        router.push(tabs.value[0].path)
      }
      break
    case 'refresh':
      router.go(0)
      break
  }
}

// 右键菜单
const handleContextMenu = (event, tab) => {
  contextTab.value = tab
  contextMenuX.value = event.clientX
  contextMenuY.value = event.clientY
  contextMenuVisible.value = true
}

const handleContextCommand = (command) => {
  if (!contextTab.value) return
  
  switch (command) {
    case 'refresh':
      if (isActive(contextTab.value)) {
        router.go(0)
      } else {
        router.push(contextTab.value.path)
        setTimeout(() => router.go(0), 100)
      }
      break
    case 'close':
      handleClose(contextTab.value)
      break
    case 'closeOthers':
      const currentPath = contextTab.value.path
      tabs.value = tabs.value.filter(t => t.fixed || t.path === currentPath)
      if (!isActive(contextTab.value)) {
        router.push(contextTab.value.path)
      }
      break
    case 'pin':
      contextTab.value.fixed = !contextTab.value.fixed
      break
    case 'copyPath':
      navigator.clipboard.writeText(contextTab.value.path)
      ElMessage.success('路径已复制')
      break
  }
  
  contextMenuVisible.value = false
}

// 滚动标签页
const scrollTabs = (direction) => {
  const scrollAmount = 200
  if (direction === 'left') {
    scrollOffset.value = Math.min(scrollOffset.value + scrollAmount, 0)
  } else {
    scrollOffset.value = Math.max(scrollOffset.value - scrollAmount, -(tabs.value.length * 150))
  }
  updateScrollButtons()
}

// 鼠标滚轮滚动
const handleWheel = (event) => {
  event.preventDefault()
  if (event.deltaY > 0) {
    scrollTabs('right')
  } else {
    scrollTabs('left')
  }
}

// 更新滚动按钮状态
const updateScrollButtons = () => {
  canScrollLeft.value = scrollOffset.value < 0
  canScrollRight.value = scrollOffset.value > -(tabs.value.length * 150 - 800)
}

// 滚动到激活的标签
const scrollToActiveTab = () => {
  const activeIndex = tabs.value.findIndex(t => isActive(t))
  if (activeIndex !== -1) {
    scrollOffset.value = -activeIndex * 150
    updateScrollButtons()
  }
}

// 标签悬停
const handleTabHover = (tab) => {
  previewTimer = setTimeout(() => {
    const tabElement = event.target.closest('.tab-item')
    if (tabElement) {
      const rect = tabElement.getBoundingClientRect()
      previewX.value = rect.left
      previewY.value = rect.bottom + 10
      previewTab.value = tab
    }
  }, 800)
}

const handleTabLeave = () => {
  clearTimeout(previewTimer)
  previewTab.value = null
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 监听路由变化
watch(() => route.path, (newPath) => {
  addTab({
    path: newPath,
    title: route.meta.title || '未命名页面',
    icon: route.meta.icon || 'Document'
  })
}, { immediate: true })

// 全局点击关闭右键菜单
const handleGlobalClick = () => {
  contextMenuVisible.value = false
}

onMounted(() => {
  document.addEventListener('click', handleGlobalClick)
  updateScrollButtons()
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleGlobalClick)
})
</script>

<style scoped>
.tab-navigation {
  height: 40px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  user-select: none;
}

.tabs-container {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
}

.tabs-control-left,
.tabs-control-right {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  padding: 0 5px;
}

.tabs-scroll {
  flex: 1;
  overflow: hidden;
  height: 100%;
}

.tabs-list {
  display: flex;
  height: 100%;
  transition: transform 0.3s;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 0 16px;
  height: 100%;
  min-width: 120px;
  max-width: 180px;
  background: #f5f7fa;
  border-right: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  flex-shrink: 0;
}

.tab-item:hover {
  background: #e4e7ed;
}

.tab-item.is-active {
  background: white;
  color: #409eff;
  font-weight: 600;
}

.tab-item.is-active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: #409eff;
}

.tab-item.is-fixed {
  background: #ecf5ff;
}

.tab-icon {
  font-size: 14px;
  flex-shrink: 0;
}

.tab-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 13px;
}

.tab-modified {
  color: #e6a23c;
  font-size: 18px;
  line-height: 1;
}

.tab-close {
  font-size: 14px;
  flex-shrink: 0;
  padding: 2px;
  border-radius: 3px;
  transition: all 0.2s;
  opacity: 0;
}

.tab-item:hover .tab-close {
  opacity: 1;
}

.tab-close:hover {
  background: #f56c6c;
  color: white;
}

.tab-fixed {
  font-size: 12px;
  color: #409eff;
  flex-shrink: 0;
}

/* 右键菜单 */
.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  padding: 4px 0;
  z-index: 9999;
  min-width: 150px;
}

.context-menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 13px;
  color: #606266;
  transition: all 0.2s;
}

.context-menu-item:hover {
  background: #ecf5ff;
  color: #409eff;
}

.context-menu-divider {
  height: 1px;
  background: #e4e7ed;
  margin: 4px 0;
}

/* 标签预览 */
.tab-preview {
  position: fixed;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  z-index: 9998;
  min-width: 200px;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.preview-path {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.preview-time {
  font-size: 12px;
  color: #c0c4cc;
}

/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>

